package com.lc.activiti.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lc.activiti.config.TreeSetting;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: TreeUtil
 * @Description:
 * @author: 骆超
 * @date: 2021/7/2 16:48
 */
public class TreeUtil {
    public static List<JSONObject> listToTree(JSONArray jsonArray, TreeSetting treeSetting){
        List<JSONObject> jsonObjectList = JSONUtil.toList(jsonArray, JSONObject.class);
        //找出所有的父级节点为空的根节点
        List<JSONObject> collect = jsonObjectList.stream().filter(v -> ObjectUtil.isEmpty(v.get(treeSetting.getParColumn()))).collect(Collectors.toList());
        collect.forEach(v->{
           findChildren(jsonObjectList,treeSetting,v,null);
        });
        return collect;
    }


    /**
     * 找到子集，放入列表中
     * @author 骆超
     * @date 2021/7/5
     * @param list 参数说明
     * @param treeSetting 参数说明
     * @param jsonObject 参数说明
     */
    public static void findChildren(List<JSONObject> list, TreeSetting treeSetting, JSONObject jsonObject,Long id){
        //找出这些子集
        List<JSONObject> collect = list.stream().filter(v -> v.getStr(treeSetting.getParColumn()).equals(jsonObject.getStr(treeSetting.getSonColumn()))&& !v.get(treeSetting.getSonColumn()).equals(id)).collect(Collectors.toList());
        collect.forEach(c->{
                c.putIfAbsent(treeSetting.getParentName(),jsonObject.get(treeSetting.getName()));
                findChildren(list,treeSetting,c,id);
        });
        //替换字段名
        treeSetting.getChangeColumn().keySet().forEach(v->{
            jsonObject.putIfAbsent(v,jsonObject.get(treeSetting.getChangeColumn().get(v)));
        });
        //使用默认值
        treeSetting.getDefaultValues().keySet().forEach(v->{
            jsonObject.putIfAbsent(v,treeSetting.getDefaultValues().get(v));
        });
        jsonObject.putIfAbsent(treeSetting.getChildrenColumn(),collect);
    }

    /**
     * 排除自身节点和子节点的树结构（选择父级节点时避免循环嵌套）
     * @author 骆超
     * @date 2021/7/5
     * @param id 所选节点的id
     * @param jsonArray 平行结构列表
     * @param treeSetting 树结构参数设置
     * @return java.util.List<cn.hutool.json.JSONObject>
     */
    public static List<JSONObject> listToTree(Long id,JSONArray jsonArray, TreeSetting treeSetting){
        List<JSONObject> jsonObjectList = JSONUtil.toList(jsonArray, JSONObject.class);
        //找出所有的父级节点为空的根节点
        List<JSONObject> collect = jsonObjectList.stream().filter(v -> ObjectUtil.isEmpty(v.get(treeSetting.getParColumn()))&& !v.get(treeSetting.getSonColumn()).equals(id) ).collect(Collectors.toList());
        collect.forEach(v->{
            findChildren(jsonObjectList,treeSetting,v,id);
        });
        return collect;
    }


}
